package com.hk.zuulservice.filter;

import com.alibaba.fastjson.JSONObject;
import com.hk.commons.CommonResult;
import com.hk.model.vo.Result;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: aerfazhe
 * @Date: 2021/8/10 15:33
 * @Statement: 过滤器统一异常处理
 */
@Component
public class ErrorFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(ErrorFilter.class);

    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_ERROR_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
//        获取上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        Throwable throwable = currentContext.getThrowable();
        logger.error("ErrorFilter....."+throwable.getCause().getMessage(),throwable);
        //        响应状态码500 服务器错误
        currentContext.setResponseStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        HttpServletResponse response = currentContext.getResponse();
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            Result result = CommonResult.errorResult("过滤器异常响应处理......");
            writer.println(JSONObject.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }

        return null;
    }

}
